package leetcode

import kotlin.math.absoluteValue

/**
 * 整数反转
 * https://leetcode.cn/problems/reverse-integer/description/
 */
class Solution_7 {

    fun reverse(x: Int): Int {
        if(x == 0) return x
        val number = "${x.absoluteValue}".reversed()
        val limit = if (x < 0){
            "2147483648"
        }else{
            "2147483647"
        }
        if (number.length > limit.length){
            return 0
        }
        if (number.length < limit.length){
           return if (x < 0){
                "-${number}".toInt()
            }else{
                number.toInt()
            }
        }
        val len = limit.length
        for (i in 0 until len) {
            if (number[i] > limit[i]) {
                return 0
            }else if(number[i] < limit[i]){
                break
            }

        }
        return if (x < 0){
            "-${number}".toInt()
        }else{
            number.toInt()
        }
    }
}